#include "server.h"
#include "database.h"
#include "auth.h"
#include "course_manager.h"
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <thread>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <signal.h>
#include <map>
#include <algorithm>

extern volatile sig_atomic_t running; // 从 main.cpp 引入

// 辅助函数：URL解码
std::string urlDecode(const std::string& str) {
    std::string decoded_str;
    char hex[3];
    for (size_t i = 0; i < str.length(); ++i) {
        if (str[i] == '%') {
            if (i + 2 < str.length()) {
                hex[0] = str[i+1];
                hex[1] = str[i+2];
                hex[2] = '\0';
                decoded_str += static_cast<char>(std::strtol(hex, nullptr, 16));
                i += 2;
            } else {
                decoded_str += str[i]; // 不完整的 % 序列
            }
        } else if (str[i] == '+') {
            decoded_str += ' ';
        } else {
            decoded_str += str[i];
        }
    }
    return decoded_str;
}

// 辅助函数：解析URL编码的表单数据
std::map<std::string, std::string> parseFormData(const std::string& data) {
    std::map<std::string, std::string> params;
    std::istringstream iss(data);
    std::string pair;

    while (std::getline(iss, pair, '&')) {
        size_t pos = pair.find('=');
        if (pos != std::string::npos) {
            std::string key = pair.substr(0, pos);
            std::string value = pair.substr(pos + 1);
            params[urlDecode(key)] = urlDecode(value);
        }
    }

    return params;
}

// 辅助函数：创建HTTP响应
std::string createResponse(const std::string& status, const std::string& message, const std::string& data = "") {
    std::stringstream ss;
    std::string json_response;

    if (status == "success") {
        json_response = "{\"success\":true,\"message\":\"" + message + "\"";
        if (!data.empty()) {
            json_response += ",\"data\":" + data;
        }
        json_response += "}";
    } else {
        json_response = "{\"success\":false,\"message\":\"" + message + "\"}";
    }

    ss << "HTTP/1.1 200 OK\r\n"
       << "Content-Type: application/json; charset=utf-8\r\n"
       << "Access-Control-Allow-Origin: *\r\n"
       << "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n"
       << "Access-Control-Allow-Headers: Content-Type\r\n"
       << "Content-Length: " << json_response.length() << "\r\n"
       << "\r\n"
       << json_response;

    return ss.str();
}

// 辅助函数：创建HTML响应
std::string createHTMLResponse(const std::string& html) {
    std::stringstream ss;
    ss << "HTTP/1.1 200 OK\r\n"
       << "Content-Type: text/html; charset=utf-8\r\n"
       << "Content-Length: " << html.length() << "\r\n"
       << "\r\n"
       << html;
    return ss.str();
}

std::string Server::processRequest(const std::string& request) {
    // 解析请求行
    size_t firstLineEnd = request.find("\r\n");
    if (firstLineEnd == std::string::npos) {
        return createResponse("error", "Invalid request");
    }

    std::string requestLine = request.substr(0, firstLineEnd);
    std::istringstream iss(requestLine);
    std::string method, fullPath, version;
    iss >> method >> fullPath >> version;

    std::cout << "Received request: " << method << " " << fullPath << std::endl;

    // 分离路径和查询参数
    std::string path = fullPath;
    size_t queryPos = fullPath.find('?');
    if (queryPos != std::string::npos) {
        path = fullPath.substr(0, queryPos);
    }

    if (method == "POST" && path == "/api/login") {
        return handleLogin(request);
    } else if (method == "GET" && path == "/api/courses") {
        return handleGetCourses();
    } else if (method == "GET" && path == "/api/student/info") {
        return handleGetStudentInfo(fullPath);
    } else if (method == "GET" && path == "/api/student/courses") {
        return handleGetStudentCourses(fullPath);
    } else if (method == "POST" && path == "/api/select-course") {
        return handleSelectCourse(request);
    } else if (method == "POST" && path == "/api/drop-course") {
        return handleDropCourse(request);
    } else if (method == "GET" && path == "/api/admin/students") {
        return handleGetAllStudents();
    } else if (method == "GET" && path == "/api/admin/teachers") {
        return handleGetAllTeachers();
    } else if (method == "GET" && path == "/api/admin/selections") {
        return handleGetAllCourseSelections();
    } else if (method == "GET" && path == "/api/teacher/courses") {
        return handleGetTeacherCourses(fullPath);
    } else if (method == "GET" && path == "/api/teacher/course/students") {
        return handleGetCourseStudents(fullPath);
    } else if (method == "GET" && path == "/") {
        return handleIndex();
    } else if (method == "OPTIONS") {
        // 处理预检请求
        std::stringstream ss;
        ss << "HTTP/1.1 200 OK\r\n"
           << "Access-Control-Allow-Origin: *\r\n"
           << "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n"
           << "Access-Control-Allow-Headers: Content-Type\r\n"
           << "Content-Length: 0\r\n"
           << "\r\n";
        return ss.str();
    }

    return createResponse("error", "接口不存在");
}

std::string Server::handleLogin(const std::string& request) {
    size_t body_start = request.find("\r\n\r\n");
    if (body_start == std::string::npos) {
        return createResponse("error", "Invalid request");
    }

    std::string body = request.substr(body_start + 4);
    auto params = parseFormData(body);

    std::string username = params["username"];
    std::string password = params["password"];

    std::cout << "Login attempt - username: '" << username << "', password: '" << password << "'" << std::endl;

    if (username.empty() || password.empty()) {
        return createResponse("error", "用户名和密码不能为空");
    }

    auto user = auth_->authenticate(username, password);
    if (user) {
        std::stringstream ss;
        ss << "{\"id\":" << user->id
           << ",\"username\":\"" << user->username
           << "\",\"role\":\"" << user->role << "\"}";
        std::string userData = ss.str();
        return createResponse("success", "登录成功", userData);
    }

    return createResponse("error", "用户名或密码错误");
}

std::string Server::handleGetCourses() {
    auto courses = courseManager_->getAllCourses();

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < courses.size(); ++i) {
        const auto& course = courses[i];
        ss << "{"
           << "\"id\":" << course.id
           << ",\"course_code\":\"" << course.course_code << "\""
           << ",\"course_name\":\"" << course.course_name << "\""
           << ",\"teacher_name\":\"" << course.teacher_name << "\""
           << ",\"description\":\"" << course.description << "\""
           << ",\"credits\":" << course.credits
           << ",\"max_students\":" << course.max_students
           << ",\"current_students\":" << course.current_students
           << ",\"semester\":\"" << course.semester << "\""
           << ",\"classroom\":\"" << course.classroom << "\""
           << ",\"schedule\":\"" << course.schedule << "\""
           << ",\"status\":\"" << course.status << "\""
           << "}";

        if (i < courses.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取课程列表成功", ss.str());
}

std::string Server::handleGetStudentInfo(const std::string& request) {
    // 从查询参数中获取user_id
    size_t query_start = request.find("?");
    if (query_start == std::string::npos) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string query = request.substr(query_start + 1);
    auto params = parseFormData(query);

    if (params.find("user_id") == params.end()) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string userIdStr = params["user_id"];
    if (userIdStr.empty()) {
        return createResponse("error", "用户ID参数为空");
    }

    int userId;
    try {
        userId = std::stoi(userIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "用户ID参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "用户ID参数超出范围");
    }

    auto student = courseManager_->getStudentByUserId(userId);

    if (!student) {
        return createResponse("error", "学生信息不存在");
    }

    std::stringstream ss;
    ss << "{"
       << "\"id\":" << student->id
       << ",\"student_id\":\"" << student->student_id << "\""
       << ",\"name\":\"" << student->name << "\""
       << ",\"gender\":\"" << student->gender << "\""
       << ",\"class_name\":\"" << student->class_name << "\""
       << ",\"email\":\"" << student->email << "\""
       << ",\"phone\":\"" << student->phone << "\""
       << "}";

    return createResponse("success", "获取学生信息成功", ss.str());
}

std::string Server::handleGetStudentCourses(const std::string& request) {
    // 从查询参数中获取user_id
    size_t query_start = request.find("?");
    if (query_start == std::string::npos) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string query = request.substr(query_start + 1);
    auto params = parseFormData(query);

    if (params.find("user_id") == params.end()) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string userIdStr = params["user_id"];
    if (userIdStr.empty()) {
        return createResponse("error", "用户ID参数为空");
    }

    int userId;
    try {
        userId = std::stoi(userIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "用户ID参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "用户ID参数超出范围");
    }
    auto student = courseManager_->getStudentByUserId(userId);

    if (!student) {
        return createResponse("error", "学生信息不存在");
    }

    auto courses = courseManager_->getStudentCourses(student->id);

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < courses.size(); ++i) {
        const auto& course = courses[i];
        ss << "{"
           << "\"id\":" << course.id
           << ",\"course_code\":\"" << course.course_code << "\""
           << ",\"course_name\":\"" << course.course_name << "\""
           << ",\"teacher_name\":\"" << course.teacher_name << "\""
           << ",\"credits\":" << course.credits
           << ",\"semester\":\"" << course.semester << "\""
           << ",\"classroom\":\"" << course.classroom << "\""
           << ",\"schedule\":\"" << course.schedule << "\""
           << "}";

        if (i < courses.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取学生选课成功", ss.str());
}

std::string Server::handleSelectCourse(const std::string& request) {
    size_t body_start = request.find("\r\n\r\n");
    if (body_start == std::string::npos) {
        return createResponse("error", "Invalid request");
    }

    std::string body = request.substr(body_start + 4);
    auto params = parseFormData(body);

    if (params.find("user_id") == params.end() || params.find("course_id") == params.end()) {
        return createResponse("error", "缺少必要参数");
    }

    std::string userIdStr = params["user_id"];
    std::string courseIdStr = params["course_id"];

    if (userIdStr.empty() || courseIdStr.empty()) {
        return createResponse("error", "参数为空");
    }

    int userId, courseId;
    try {
        userId = std::stoi(userIdStr);
        courseId = std::stoi(courseIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "参数超出范围");
    }

    auto student = courseManager_->getStudentByUserId(userId);
    if (!student) {
        return createResponse("error", "学生信息不存在");
    }

    if (!courseManager_->courseExists(courseId)) {
        return createResponse("error", "课程不存在");
    }

    if (courseManager_->selectCourse(student->id, courseId)) {
        return createResponse("success", "选课成功");
    } else {
        return createResponse("error", "选课失败，课程可能已满或已选");
    }
}

std::string Server::handleDropCourse(const std::string& request) {
    size_t body_start = request.find("\r\n\r\n");
    if (body_start == std::string::npos) {
        return createResponse("error", "Invalid request");
    }

    std::string body = request.substr(body_start + 4);
    auto params = parseFormData(body);

    if (params.find("user_id") == params.end() || params.find("course_id") == params.end()) {
        return createResponse("error", "缺少必要参数");
    }

    std::string userIdStr = params["user_id"];
    std::string courseIdStr = params["course_id"];

    if (userIdStr.empty() || courseIdStr.empty()) {
        return createResponse("error", "参数为空");
    }

    int userId, courseId;
    try {
        userId = std::stoi(userIdStr);
        courseId = std::stoi(courseIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "参数超出范围");
    }

    auto student = courseManager_->getStudentByUserId(userId);
    if (!student) {
        return createResponse("error", "学生信息不存在");
    }

    if (courseManager_->dropCourse(student->id, courseId)) {
        return createResponse("success", "退课成功");
    } else {
        return createResponse("error", "退课失败");
    }
}

std::string Server::handleIndex() {
    std::string html = R"html(
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生选课系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        .content {
            padding: 40px;
        }
        .login-section, .main-section {
            margin-bottom: 40px;
        }
        .login-form {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        .form-group input:focus {
            outline: none;
            border-color: #4facfe;
        }
        .btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s ease;
        }
        .btn:hover {
            transform: translateY(-2px);
        }
        .btn:active {
            transform: scale(0.98);
        }
        .course-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        .course-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .course-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        }
        .course-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
        }
        .course-title {
            font-size: 1.3em;
            margin-bottom: 8px;
            font-weight: 600;
        }
        .course-code {
            font-size: 0.9em;
            opacity: 0.8;
            margin-bottom: 5px;
        }
        .course-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 500;
        }
        .status-available {
            background: rgba(40, 167, 69, 0.2);
            color: #28a745;
        }
        .status-full {
            background: rgba(220, 53, 69, 0.2);
            color: #dc3545;
        }
        .course-body {
            padding: 20px;
        }
        .course-info {
            margin-bottom: 15px;
        }
        .course-info p {
            margin-bottom: 8px;
            color: #666;
            font-size: 0.9em;
        }
        .course-info strong {
            color: #333;
        }
        .course-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        .btn-select, .btn-drop {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 6px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .btn-select {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        .btn-select:hover:not(:disabled) {
            transform: translateY(-2px);
        }
        .btn-drop {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }
        .btn-drop:hover:not(:disabled) {
            transform: translateY(-2px);
        }
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .student-info {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .student-info h3 {
            margin-bottom: 15px;
            font-size: 1.2em;
        }
        .student-info p {
            margin-bottom: 5px;
            opacity: 0.9;
        }
        .nav-tabs {
            display: flex;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 5px;
            margin-bottom: 30px;
        }
        .nav-tab {
            flex: 1;
            padding: 10px;
            text-align: center;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        .nav-tab.active {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        .alert-success {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
            border: 1px solid rgba(40, 167, 69, 0.2);
        }
        .alert-error {
            background: rgba(220, 53, 69, 0.1);
            color: #dc3545;
            border: 1px solid rgba(220, 53, 69, 0.2);
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .admin-list {
            margin-top: 20px;
            background: #e9ecef;
            padding: 20px;
            border-radius: 8px;
            min-height: 200px;
            border: 2px solid #007bff;
            color: #000;
        }

        .admin-item {
            background: #ffffff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border-left: 4px solid #4facfe;
            border: 1px solid #ddd;
            color: #333;
        }

        .admin-item h4 {
            margin: 0 0 8px 0;
            color: #000 !important;
            font-size: 1.1em;
            font-weight: bold;
        }

        .admin-item p {
            margin: 4px 0;
            color: #333 !important;
            font-size: 0.9em;
        }

        .admin-item .status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: 500;
        }

        .status-selected {
            background: rgba(40, 167, 69, 0.2);
            color: #28a745;
        }

        .status-dropped {
            background: rgba(220, 53, 69, 0.2);
            color: #dc3545;
        }

        .view-students-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.8em;
            margin-top: 8px;
        }

        .view-students-btn:hover {
            transform: translateY(-1px);
        }

        .students-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .students-modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            width: 90%;
        }

        .close-modal {
            position: absolute;
            top: 10px;
            right: 15px;
            font-size: 24px;
            cursor: pointer;
            color: #666;
        }

        @media (max-width: 768px) {
            .content {
                padding: 20px;
            }
            .course-grid {
                grid-template-columns: 1fr;
            }
            .admin-list {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎓 学生选课系统</h1>
            <p>现代化在线选课平台</p>
        </div>
        <div class="content">
            <!-- 登录部分 -->
            <div id="login-section">
                <div class="login-form">
                    <div class="form-group">
                        <label>👤 用户名</label>
                        <input type="text" id="username" placeholder="请输入用户名" required>
                    </div>
                    <div class="form-group">
                        <label>🔒 密码</label>
                        <input type="password" id="password" placeholder="请输入密码" required>
                    </div>
                    <button class="btn" onclick="login()">登录</button>
                </div>
            </div>

            <!-- 主界面 -->
            <div id="main-section" style="display: none;">
                <!-- 学生信息 -->
        <!-- 学生信息 -->
        <div id="student-info" class="student-info" style="display: none;">
            <h3>📋 学生信息</h3>
            <p id="student-details">加载中...</p>
        </div>

        <!-- 教师信息 -->
        <div id="teacher-info" class="student-info" style="display: none;">
            <h3>👨‍🏫 教师信息</h3>
            <p id="teacher-details">加载中...</p>
        </div>

        <!-- 导航标签 -->
        <div class="nav-tabs" id="nav-tabs">
            <div class="nav-tab active" onclick="switchTab('courses')">📚 课程列表</div>
            <div class="nav-tab" onclick="switchTab('my-courses')">📖 我的课程</div>
        </div>

        <!-- 课程列表标签页 -->
        <div id="courses-tab" class="tab-content active">
            <div id="courses-list" class="course-grid">
                <div class="loading">加载中...</div>
            </div>
        </div>

        <!-- 我的课程标签页 -->
        <div id="my-courses-tab" class="tab-content">
            <div id="my-courses-list" class="course-grid">
                <div class="loading">加载中...</div>
            </div>
        </div>

        <!-- 教师课程标签页 -->
        <div id="teacher-courses-tab" class="tab-content">
            <div id="teacher-courses-list" class="course-grid">
                <div class="loading">加载中...</div>
            </div>
        </div>

        <!-- 管理员标签页 -->
        <div class="nav-tabs" id="admin-nav-tabs" style="display: none;">
            <div class="nav-tab active" onclick="switchAdminTab('students')">👥 学生管理</div>
            <div class="nav-tab" onclick="switchAdminTab('teachers')">👨‍🏫 教师管理</div>
            <div class="nav-tab" onclick="switchAdminTab('selections')">📊 选课记录</div>
        </div>

        <!-- 管理员内容 -->
        <div id="admin-content" style="display: none;">
            <div id="admin-students-tab" class="tab-content active">
                <h3>👥 所有学生</h3>
                <div id="admin-students-list" class="admin-list" style="background: yellow; padding: 10px; border: 3px solid green;">
                    <div class="loading">加载中...</div>
                </div>
            </div>

            <div id="admin-teachers-tab" class="tab-content">
                <h3>👨‍🏫 所有教师</h3>
                <div id="admin-teachers-list" class="admin-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>

            <div id="admin-selections-tab" class="tab-content">
                <h3>📊 选课记录</h3>
                <div id="admin-selections-list" class="admin-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
            </div>
        </div>
    </div>

    <script>
        let currentUser = null;
        let currentTab = 'courses';

        // 登录功能
        async function login() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!username || !password) {
                showAlert('请输入用户名和密码', 'error');
                return;
            }

            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
                });

                const result = await response.json();
                console.log('Login response:', result);

                if (result.success) {
                    currentUser = result.data;
                    showAlert('登录成功！', 'success');

                    // 隐藏登录，显示主界面
                    document.getElementById('login-section').style.display = 'none';
                    document.getElementById('main-section').style.display = 'block';

                    // 初始化界面并加载数据
                    onLoginSuccess();
                } else {
                    showAlert(result.message || '登录失败', 'error');
                }
            } catch (error) {
                console.error('Login error:', error);
                showAlert('网络错误，请重试', 'error');
            }
        }

        // 加载学生信息
        async function loadStudentInfo() {
            if (!currentUser) return;

            try {
                const response = await fetch(`/api/student/info?user_id=${currentUser.id}`);
                const result = await response.json();

                if (result.success) {
                    const student = result.data;
                    document.getElementById('student-details').innerHTML = `
                        学号: ${student.student_id}<br>
                        姓名: ${student.name}<br>
                        性别: ${student.gender}<br>
                        班级: ${student.class_name}<br>
                        邮箱: ${student.email}<br>
                        电话: ${student.phone}
                    `;
                    document.getElementById('student-info').style.display = 'block';
                }
            } catch (error) {
                console.error('Load student info error:', error);
            }
        }

        // 加载课程列表
        async function loadCourses() {
            try {
                const response = await fetch('/api/courses');
                const result = await response.json();

                if (result.success) {
                    displayCourses(result.data);
                } else {
                    showAlert('加载课程失败', 'error');
                }
            } catch (error) {
                console.error('Load courses error:', error);
                showAlert('网络错误', 'error');
            }
        }

        // 加载我的课程
        async function loadMyCourses() {
            if (!currentUser) return;

            try {
                const response = await fetch(`/api/student/courses?user_id=${currentUser.id}`);
                const result = await response.json();

                if (result.success) {
                    displayMyCourses(result.data);
                }
            } catch (error) {
                console.error('Load my courses error:', error);
            }
        }

        // 显示课程列表
        function displayCourses(courses) {
            const container = document.getElementById('courses-list');
            container.innerHTML = '';

            if (courses.length === 0) {
                container.innerHTML = '<div class="loading">暂无课程</div>';
                return;
            }

            courses.forEach(course => {
                const card = document.createElement('div');
                card.className = 'course-card';

                const statusClass = course.status === '可选' ? 'status-available' : 'status-full';
                const isStudent = currentUser && currentUser.role === 'student';
                const canSelect = isStudent && course.status === '可选';

                card.innerHTML = `
                    <div class="course-header">
                        <div class="course-title">${course.course_name}</div>
                        <div class="course-code">${course.course_code}</div>
                        <span class="course-status ${statusClass}">${course.status}</span>
                    </div>
                    <div class="course-body">
                        <div class="course-info">
                            <p><strong>教师：</strong>${course.teacher_name}</p>
                            <p><strong>学分：</strong>${course.credits}</p>
                            <p><strong>学期：</strong>${course.semester}</p>
                            <p><strong>教室：</strong>${course.classroom}</p>
                            <p><strong>时间：</strong>${course.schedule}</p>
                            <p><strong>已选/容量：</strong>${course.current_students}/${course.max_students}</p>
                            <p><strong>课程描述：</strong>${course.description}</p>
                        </div>
                        ${isStudent ? `
                        <div class="course-actions">
                            <button class="btn-select" onclick="selectCourse(${course.id})" ${!canSelect ? 'disabled' : ''}>
                                选课
                            </button>
                        </div>
                        ` : ''}
                    </div>
                `;

                container.appendChild(card);
            });
        }

        // 显示我的课程
        function displayMyCourses(courses) {
            const container = document.getElementById('my-courses-list');
            container.innerHTML = '';

            if (courses.length === 0) {
                container.innerHTML = '<div class="loading">暂无选课记录</div>';
                return;
            }

            courses.forEach(course => {
                const card = document.createElement('div');
                card.className = 'course-card';

                card.innerHTML = `
                    <div class="course-header">
                        <div class="course-title">${course.course_name}</div>
                        <div class="course-code">${course.course_code}</div>
                        <span class="course-status status-available">已选</span>
                    </div>
                    <div class="course-body">
                        <div class="course-info">
                            <p><strong>教师：</strong>${course.teacher_name}</p>
                            <p><strong>学分：</strong>${course.credits}</p>
                            <p><strong>学期：</strong>${course.semester}</p>
                            <p><strong>教室：</strong>${course.classroom}</p>
                            <p><strong>时间：</strong>${course.schedule}</p>
                        </div>
                        <div class="course-actions">
                            <button class="btn-drop" onclick="dropCourse(${course.id})">
                                退课
                            </button>
                        </div>
                    </div>
                `;

                container.appendChild(card);
            });
        }

        // 选课功能
        async function selectCourse(courseId) {
            if (!currentUser) {
                showAlert('请先登录', 'error');
                return;
            }

            try {
                const response = await fetch('/api/select-course', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `user_id=${currentUser.id}&course_id=${courseId}`
                });

                const result = await response.json();

                if (result.success) {
                    showAlert('选课成功！', 'success');
                    loadCourses(); // 刷新课程列表
                    loadMyCourses(); // 刷新我的课程
                } else {
                    showAlert(result.message || '选课失败', 'error');
                }
            } catch (error) {
                console.error('Select course error:', error);
                showAlert('网络错误', 'error');
            }
        }

        // 退课功能
        async function dropCourse(courseId) {
            if (!currentUser) {
                showAlert('请先登录', 'error');
                return;
            }

            if (!confirm('确定要退选这门课程吗？')) {
                return;
            }

            try {
                const response = await fetch('/api/drop-course', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: `user_id=${currentUser.id}&course_id=${courseId}`
                });

                const result = await response.json();

                if (result.success) {
                    showAlert('退课成功！', 'success');
                    loadCourses(); // 刷新课程列表
                    loadMyCourses(); // 刷新我的课程
                } else {
                    showAlert(result.message || '退课失败', 'error');
                }
            } catch (error) {
                console.error('Drop course error:', error);
                showAlert('网络错误', 'error');
            }
        }

        // 切换标签页
        function switchTab(tab) {
            currentTab = tab;

            // 更新标签状态
            document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
            document.querySelector(`[onclick="switchTab('${tab}')"]`).classList.add('active');

            // 更新内容区域
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.getElementById(`${tab}-tab`).classList.add('active');

            // 加载对应数据
            if (tab === 'courses') {
                loadCourses();
            } else if (tab === 'my-courses') {
                loadMyCourses();
            }
        }

        // 显示提示信息
        function showAlert(message, type) {
            // 移除现有提示
            const existing = document.querySelector('.alert');
            if (existing) {
                existing.remove();
            }

            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;

            const container = document.querySelector('.content');
            container.insertBefore(alert, container.firstChild);

            // 3秒后自动移除
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.remove();
                }
            }, 3000);
        }

        // 加载教师信息
        async function loadTeacherInfo() {
            if (!currentUser) return;

            try {
                const response = await fetch(`/api/teacher/courses?user_id=${currentUser.id}`);
                const result = await response.json();

                if (result.success && result.data.length > 0) {
                    const courseCount = result.data.length;
                    document.getElementById('teacher-details').innerHTML = `
                        教授课程数量: ${courseCount} 门<br>
                        请选择课程查看选课学生
                    `;
                    document.getElementById('teacher-info').style.display = 'block';
                }
            } catch (error) {
                console.error('Load teacher info error:', error);
            }
        }

        // 加载教师课程
        async function loadTeacherCourses() {
            if (!currentUser) return;

            try {
                const response = await fetch(`/api/teacher/courses?user_id=${currentUser.id}`);
                const result = await response.json();

                if (result.success) {
                    displayTeacherCourses(result.data);
                }
            } catch (error) {
                console.error('Load teacher courses error:', error);
            }
        }

        // 显示教师课程
        function displayTeacherCourses(courses) {
            const container = document.getElementById('teacher-courses-list');
            container.innerHTML = '';

            if (courses.length === 0) {
                container.innerHTML = '<div class="loading">暂无教授课程</div>';
                return;
            }

            courses.forEach(course => {
                const card = document.createElement('div');
                card.className = 'course-card';

                card.innerHTML = `
                    <div class="course-header">
                        <div class="course-title">${course.course_name}</div>
                        <div class="course-code">${course.course_code}</div>
                        <span class="course-status status-available">教授中</span>
                    </div>
                    <div class="course-body">
                        <div class="course-info">
                            <p><strong>学分：</strong>${course.credits}</p>
                            <p><strong>学期：</strong>${course.semester}</p>
                            <p><strong>教室：</strong>${course.classroom}</p>
                            <p><strong>时间：</strong>${course.schedule}</p>
                            <p><strong>已选/容量：</strong>${course.current_students}/${course.max_students}</p>
                        </div>
                        <div class="course-actions">
                            <button class="btn" onclick="viewCourseStudents(${course.id})">
                                👥 查看选课学生
                            </button>
                        </div>
                    </div>
                `;

                container.appendChild(card);
            });
        }

        // 查看课程选课学生
        async function viewCourseStudents(courseId) {
            try {
                const response = await fetch(`/api/teacher/course/students?course_id=${courseId}`);
                const result = await response.json();

                if (result.success) {
                    showStudentsModal(result.data);
                } else {
                    alert('获取学生列表失败');
                }
            } catch (error) {
                console.error('View course students error:', error);
                alert('网络错误');
            }
        }

        // 显示学生模态框
        function showStudentsModal(students) {
            let modal = document.getElementById('students-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'students-modal';
                modal.className = 'students-modal';
                modal.innerHTML = `
                    <div class="students-modal-content">
                        <span class="close-modal" onclick="closeStudentsModal()">&times;</span>
                        <h3>📚 选课学生列表</h3>
                        <div id="modal-students-list"></div>
                    </div>
                `;
                document.body.appendChild(modal);
            }

            const list = document.getElementById('modal-students-list');
            if (students.length === 0) {
                list.innerHTML = '<p>暂无学生选课</p>';
            } else {
                list.innerHTML = students.map(student => `
                    <div class="admin-item">
                        <h4>${student.student_name}</h4>
                        <p><strong>选课时间：</strong>${student.selection_time}</p>
                        <p><strong>状态：</strong><span class="status status-selected">${student.status}</span></p>
                    </div>
                `).join('');
            }

            modal.style.display = 'block';
        }

        // 关闭学生模态框
        function closeStudentsModal() {
            const modal = document.getElementById('students-modal');
            if (modal) {
                modal.style.display = 'none';
            }
        }

        // 加载管理员数据
        async function loadAdminData() {
            console.log('loadAdminData called');
            try {
                await loadAdminStudents();
                console.log('loadAdminStudents completed');
                await loadAdminTeachers();
                console.log('loadAdminTeachers completed');
                await loadAdminSelections();
                console.log('loadAdminSelections completed');
            } catch (error) {
                console.error('loadAdminData error:', error);
            }
        }

        // 加载管理员学生列表
        async function loadAdminStudents() {
            try {
                const response = await fetch('/api/admin/students');
                const result = await response.json();

                if (result.success) {
                    displayAdminStudents(result.data);
                }
            } catch (error) {
                console.error('Load admin students error:', error);
            }
        }

        // 加载管理员教师列表
        async function loadAdminTeachers() {
            try {
                const response = await fetch('/api/admin/teachers');
                const result = await response.json();

                if (result.success) {
                    displayAdminTeachers(result.data);
                }
            } catch (error) {
                console.error('Load admin teachers error:', error);
            }
        }

        // 加载管理员选课记录
        async function loadAdminSelections() {
            try {
                const response = await fetch('/api/admin/selections');
                const result = await response.json();

                if (result.success) {
                    displayAdminSelections(result.data);
                }
            } catch (error) {
                console.error('Load admin selections error:', error);
            }
        }

        // 显示管理员学生列表
        function displayAdminStudents(students) {
            console.log('displayAdminStudents called with', students.length, 'students');
            const container = document.getElementById('admin-students-list');
            console.log('Container element:', container);

            if (!container) {
                console.error('admin-students-list element not found');
                return;
            }

            container.innerHTML = '';

            if (students.length === 0) {
                container.innerHTML = '<div class="loading">暂无学生数据</div>';
                return;
            }

            students.forEach(student => {
                console.log('Rendering student:', student);
                const item = document.createElement('div');
                item.className = 'admin-item';

                item.innerHTML = `
                    <h4>${student.name} (${student.student_id})</h4>
                    <p><strong>性别：</strong>${student.gender}</p>
                    <p><strong>班级：</strong>${student.class_name}</p>
                    <p><strong>邮箱：</strong>${student.email}</p>
                    <p><strong>电话：</strong>${student.phone}</p>
                `;

                console.log('Created item HTML:', item.innerHTML);
                container.appendChild(item);
            });

            console.log('Final container HTML:', container.innerHTML);
        }

        // 显示管理员教师列表
        function displayAdminTeachers(teachers) {
            const container = document.getElementById('admin-teachers-list');
            container.innerHTML = '';

            if (teachers.length === 0) {
                container.innerHTML = '<div class="loading">暂无教师数据</div>';
                return;
            }

            teachers.forEach(teacher => {
                const item = document.createElement('div');
                item.className = 'admin-item';

                item.innerHTML = `
                    <h4>${teacher.name} (${teacher.teacher_id})</h4>
                    <p><strong>部门：</strong>${teacher.department}</p>
                    <p><strong>邮箱：</strong>${teacher.email}</p>
                    <p><strong>电话：</strong>${teacher.phone}</p>
                `;

                container.appendChild(item);
            });
        }

        // 显示管理员选课记录
        function displayAdminSelections(selections) {
            const container = document.getElementById('admin-selections-list');
            container.innerHTML = '';

            if (selections.length === 0) {
                container.innerHTML = '<div class="loading">暂无选课记录</div>';
                return;
            }

            selections.forEach(selection => {
                const item = document.createElement('div');
                item.className = 'admin-item';

                const statusClass = selection.status === '已选' ? 'status-selected' : 'status-dropped';

                item.innerHTML = `
                    <h4>${selection.student_name} → ${selection.course_name}</h4>
                    <p><strong>选课时间：</strong>${selection.selection_time}</p>
                    <p><strong>状态：</strong><span class="status ${statusClass}">${selection.status}</span></p>
                `;

                container.appendChild(item);
            });
        }

        // 切换标签页（教师）
        function switchTeacherTab(tab) {
            document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
            document.querySelector(`[onclick="switchTeacherTab('${tab}')"]`).classList.add('active');

            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            document.getElementById(`${tab}-tab`).classList.add('active');

            if (tab === 'teacher-courses') {
                loadTeacherCourses();
            }
        }

        // 切换管理员标签页
        function switchAdminTab(tab) {
            document.querySelectorAll('#admin-nav-tabs .nav-tab').forEach(t => t.classList.remove('active'));
            event.target.classList.add('active');

            document.querySelectorAll('#admin-content .tab-content').forEach(c => c.classList.remove('active'));
            document.getElementById(`admin-${tab}-tab`).classList.add('active');
        }

        // 根据用户角色初始化界面
        function initializeInterface() {
            console.log('initializeInterface called, currentUser:', currentUser);
            if (currentUser) {
                console.log('User role:', currentUser.role);
                if (currentUser.role === 'admin') {
                    console.log('Setting up admin interface - completely rewritten');

                    // 完全重写管理员界面：直接替换整个页面
                    document.body.innerHTML = `
                        <div style="font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; min-height: 100vh;">
                            <h1 style="color: #333; text-align: center; margin-bottom: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px;">🎓 学生选课系统 - 管理员面板</h1>

                            <div style="max-width: 1200px; margin: 0 auto;">
                                <!-- 导航按钮 -->
                                <div style="display: flex; gap: 20px; margin-bottom: 30px; justify-content: center;">
                                    <button onclick="showStudents()" style="padding: 15px 30px; background: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
                                        👥 查看所有学生
                                    </button>
                                    <button onclick="showTeachers()" style="padding: 15px 30px; background: #28a745; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
                                        👨‍🏫 查看所有教师
                                    </button>
                                    <button onclick="showSelections()" style="padding: 15px 30px; background: #dc3545; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: bold; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
                                        📊 查看选课记录
                                    </button>
                                </div>

                                <!-- 内容区域 -->
                                <div id="admin-content-area" style="background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); min-height: 500px;">
                                    <h2 style="color: #333; margin-bottom: 20px; text-align: center;">欢迎使用管理员面板</h2>
                                    <p style="color: #666; font-size: 18px; text-align: center;">请选择上方按钮查看相应信息。</p>
                                </div>
                            </div>
                        </div>
                    `;

                    // 定义管理员功能函数
                    window.showStudents = async function() {
                        const contentArea = document.getElementById('admin-content-area');
                        contentArea.innerHTML = '<h2 style="text-align: center;">👥 学生列表</h2><p style="text-align: center; font-size: 18px;">正在加载...</p>';

                        try {
                            const response = await fetch('/api/admin/students');
                            const result = await response.json();

                            if (result.success && result.data.length > 0) {
                                let html = '<h2 style="text-align: center; margin-bottom: 30px;">👥 所有学生信息</h2>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 20px;">';

                                result.data.forEach(student => {
                                    html += `
                                        <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                            <h3 style="color: #495057; margin: 0 0 15px 0; border-bottom: 2px solid #007bff; padding-bottom: 10px;">
                                                ${student.name}
                                            </h3>
                                            <div style="line-height: 1.6;">
                                                <p style="margin: 8px 0;"><strong>学号:</strong> ${student.student_id}</p>
                                                <p style="margin: 8px 0;"><strong>性别:</strong> ${student.gender}</p>
                                                <p style="margin: 8px 0;"><strong>班级:</strong> ${student.class_name}</p>
                                                <p style="margin: 8px 0;"><strong>邮箱:</strong> ${student.email}</p>
                                                <p style="margin: 8px 0;"><strong>电话:</strong> ${student.phone}</p>
                                            </div>
                                        </div>
                                    `;
                                });

                                html += '</div>';
                                contentArea.innerHTML = html;
                            } else {
                                contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 暂无学生数据</h2>';
                            }
                        } catch (error) {
                            contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 网络错误</h2><p style="text-align: center;">无法加载学生数据</p>';
                        }
                    };

                    window.showTeachers = async function() {
                        const contentArea = document.getElementById('admin-content-area');
                        contentArea.innerHTML = '<h2 style="text-align: center;">👨‍🏫 教师列表</h2><p style="text-align: center; font-size: 18px;">正在加载...</p>';

                        try {
                            const response = await fetch('/api/admin/teachers');
                            const result = await response.json();

                            if (result.success && result.data.length > 0) {
                                let html = '<h2 style="text-align: center; margin-bottom: 30px;">👨‍🏫 所有教师信息</h2>';
                                html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 20px;">';

                                result.data.forEach(teacher => {
                                    html += `
                                        <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                            <h3 style="color: #495057; margin: 0 0 15px 0; border-bottom: 2px solid #28a745; padding-bottom: 10px;">
                                                ${teacher.name}
                                            </h3>
                                            <div style="line-height: 1.6;">
                                                <p style="margin: 8px 0;"><strong>教师编号:</strong> ${teacher.teacher_id}</p>
                                                <p style="margin: 8px 0;"><strong>部门:</strong> ${teacher.department}</p>
                                                <p style="margin: 8px 0;"><strong>邮箱:</strong> ${teacher.email}</p>
                                                <p style="margin: 8px 0;"><strong>电话:</strong> ${teacher.phone}</p>
                                            </div>
                                        </div>
                                    `;
                                });

                                html += '</div>';
                                contentArea.innerHTML = html;
                            } else {
                                contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 暂无教师数据</h2>';
                            }
                        } catch (error) {
                            contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 网络错误</h2><p style="text-align: center;">无法加载教师数据</p>';
                        }
                    };

                    window.showSelections = async function() {
                        const contentArea = document.getElementById('admin-content-area');
                        contentArea.innerHTML = '<h2 style="text-align: center;">📊 选课记录</h2><p style="text-align: center; font-size: 18px;">正在加载...</p>';

                        try {
                            const response = await fetch('/api/admin/selections');
                            const result = await response.json();

                            if (result.success && result.data.length > 0) {
                                let html = '<h2 style="text-align: center; margin-bottom: 30px;">📊 选课记录统计</h2>';
                                html += '<div style="margin-bottom: 20px; text-align: center; background: #e9ecef; padding: 15px; border-radius: 8px;">';
                                html += `<h3 style="margin: 0; color: #495057;">总记录数: ${result.data.length}</h3>`;
                                html += '</div>';

                                html += '<div style="max-height: 600px; overflow-y: auto;">';

                                result.data.forEach(selection => {
                                    const statusColor = selection.status === '已选' ? '#28a745' : '#dc3545';
                                    const statusBg = selection.status === '已选' ? '#d4edda' : '#f8d7da';
                                    const borderColor = selection.status === '已选' ? '#c3e6cb' : '#f5c6cb';

                                    html += `
                                        <div style="background: white; border: 1px solid ${borderColor}; border-radius: 8px; padding: 15px; margin: 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                                <h4 style="margin: 0; color: #495057;">
                                                    ${selection.student_name} → ${selection.course_name}
                                                </h4>
                                                <span style="background: ${statusBg}; color: ${statusColor}; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: bold;">
                                                    ${selection.status}
                                                </span>
                                            </div>
                                            <p style="margin: 5px 0; color: #6c757d; font-size: 14px;">
                                                <strong>选课时间:</strong> ${selection.selection_time}
                                            </p>
                                        </div>
                                    `;
                                });

                                html += '</div>';
                                contentArea.innerHTML = html;
                            } else {
                                contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 暂无选课记录</h2>';
                            }
                        } catch (error) {
                            contentArea.innerHTML = '<h2 style="text-align: center; color: #dc3545;">❌ 网络错误</h2><p style="text-align: center;">无法加载选课记录</p>';
                        }
                    };

                    console.log('Admin interface completely rewritten and loaded');
                } else if (currentUser.role === 'teacher') {
                    console.log('Setting up teacher interface');
                    document.getElementById('nav-tabs').innerHTML = `
                        <div class="nav-tab active" onclick="switchTeacherTab('teacher-courses')">📚 我的课程</div>
                    `;
                    document.querySelector('h1').textContent = '🎓 学生选课系统 - 教师面板';
                } else {
                    console.log('Setting up student interface');
                    document.querySelector('h1').textContent = '🎓 学生选课系统 - 学生面板';
                }
            } else {
                console.log('No currentUser found');
            }
        }

        // 修改登录成功后的处理
        function onLoginSuccess() {
            initializeInterface();

            if (currentUser.role === 'admin') {
                loadAdminData();
            } else if (currentUser.role === 'teacher') {
                loadTeacherInfo();
                loadTeacherCourses();
            } else {
                loadStudentInfo();
                loadCourses();
            }
        }

        // 回车键登录
        document.getElementById('username').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('password').focus();
            }
        });

        document.getElementById('password').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                login();
            }
        });
    </script>
</body>
</html>
)html";

    return createHTMLResponse(html);
}

std::string Server::handleGetAllStudents() {
    auto students = courseManager_->getAllStudents();

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < students.size(); ++i) {
        const auto& student = students[i];
        ss << "{"
           << "\"id\":" << student.id
           << ",\"user_id\":" << student.user_id
           << ",\"student_id\":\"" << student.student_id << "\""
           << ",\"name\":\"" << student.name << "\""
           << ",\"gender\":\"" << student.gender << "\""
           << ",\"class_name\":\"" << student.class_name << "\""
           << ",\"email\":\"" << student.email << "\""
           << ",\"phone\":\"" << student.phone << "\""
           << "}";

        if (i < students.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取学生列表成功", ss.str());
}

std::string Server::handleGetAllTeachers() {
    auto teachers = courseManager_->getAllTeachers();

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < teachers.size(); ++i) {
        const auto& teacher = teachers[i];
        ss << "{"
           << "\"id\":" << teacher.id
           << ",\"user_id\":" << teacher.user_id
           << ",\"teacher_id\":\"" << teacher.teacher_id << "\""
           << ",\"name\":\"" << teacher.name << "\""
           << ",\"department\":\"" << teacher.department << "\""
           << ",\"email\":\"" << teacher.email << "\""
           << ",\"phone\":\"" << teacher.phone << "\""
           << "}";

        if (i < teachers.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取教师列表成功", ss.str());
}

std::string Server::handleGetAllCourseSelections() {
    auto selections = courseManager_->getAllCourseSelections();

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < selections.size(); ++i) {
        const auto& selection = selections[i];
        ss << "{"
           << "\"id\":" << selection.id
           << ",\"student_id\":" << selection.student_id
           << ",\"course_id\":" << selection.course_id
           << ",\"student_name\":\"" << selection.student_name << "\""
           << ",\"course_name\":\"" << selection.course_name << "\""
           << ",\"selection_time\":\"" << selection.selection_time << "\""
           << ",\"status\":\"" << selection.status << "\""
           << "}";

        if (i < selections.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取选课记录成功", ss.str());
}

std::string Server::handleGetTeacherCourses(const std::string& request) {
    size_t query_start = request.find("?");
    if (query_start == std::string::npos) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string query = request.substr(query_start + 1);
    auto params = parseFormData(query);

    if (params.find("user_id") == params.end()) {
        return createResponse("error", "缺少用户ID参数");
    }

    std::string userIdStr = params["user_id"];
    if (userIdStr.empty()) {
        return createResponse("error", "用户ID参数为空");
    }

    int userId;
    try {
        userId = std::stoi(userIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "用户ID参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "用户ID参数超出范围");
    }

    auto teacher = courseManager_->getTeacherByUserId(userId);
    if (!teacher) {
        return createResponse("error", "教师信息不存在");
    }

    auto courses = courseManager_->getTeacherCourses(teacher->id);

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < courses.size(); ++i) {
        const auto& course = courses[i];
        ss << "{"
           << "\"id\":" << course.id
           << ",\"course_code\":\"" << course.course_code << "\""
           << ",\"course_name\":\"" << course.course_name << "\""
           << ",\"description\":\"" << course.description << "\""
           << ",\"credits\":" << course.credits
           << ",\"max_students\":" << course.max_students
           << ",\"current_students\":" << course.current_students
           << ",\"semester\":\"" << course.semester << "\""
           << ",\"classroom\":\"" << course.classroom << "\""
           << ",\"schedule\":\"" << course.schedule << "\""
           << ",\"status\":\"" << course.status << "\""
           << "}";

        if (i < courses.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取教师课程成功", ss.str());
}

std::string Server::handleGetCourseStudents(const std::string& request) {
    size_t query_start = request.find("?");
    if (query_start == std::string::npos) {
        return createResponse("error", "缺少课程ID参数");
    }

    std::string query = request.substr(query_start + 1);
    auto params = parseFormData(query);

    if (params.find("course_id") == params.end()) {
        return createResponse("error", "缺少课程ID参数");
    }

    std::string courseIdStr = params["course_id"];
    if (courseIdStr.empty()) {
        return createResponse("error", "课程ID参数为空");
    }

    int courseId;
    try {
        courseId = std::stoi(courseIdStr);
    } catch (const std::invalid_argument& e) {
        return createResponse("error", "课程ID参数无效");
    } catch (const std::out_of_range& e) {
        return createResponse("error", "课程ID参数超出范围");
    }

    if (!courseManager_->courseExists(courseId)) {
        return createResponse("error", "课程不存在");
    }

    auto selections = courseManager_->getCourseSelectionsByCourseId(courseId);

    std::stringstream ss;
    ss << "[";

    for (size_t i = 0; i < selections.size(); ++i) {
        const auto& selection = selections[i];
        ss << "{"
           << "\"id\":" << selection.id
           << ",\"student_id\":" << selection.student_id
           << ",\"course_id\":" << selection.course_id
           << ",\"student_name\":\"" << selection.student_name << "\""
           << ",\"course_name\":\"" << selection.course_name << "\""
           << ",\"selection_time\":\"" << selection.selection_time << "\""
           << ",\"status\":\"" << selection.status << "\""
           << "}";

        if (i < selections.size() - 1) {
            ss << ",";
        }
    }

    ss << "]";

    return createResponse("success", "获取课程选课学生成功", ss.str());
}

void handleClient(int client_fd, Server* server) {
    char buffer[4096] = {0};
    ssize_t bytes_read = read(client_fd, buffer, sizeof(buffer) - 1);
    if (bytes_read > 0) {
        std::string request(buffer, bytes_read);
        std::string response = server->processRequest(request);
        send(client_fd, response.c_str(), response.length(), 0);
    }
    close(client_fd);
}

Server::Server() : server_fd_(-1) {
    std::cout << "初始化学生选课系统..." << std::endl;

    // 初始化数据库连接
    db_ = std::make_unique<Database>();
    if (!db_->connect()) {
        throw std::runtime_error("数据库连接失败");
    }

    // 初始化认证模块
    auth_ = std::make_unique<Auth>(db_.get());

    // 初始化课程管理模块
    courseManager_ = std::make_unique<CourseManager>(db_.get());

    std::cout << "系统初始化完成" << std::endl;
}

Server::~Server() {
    if (server_fd_ >= 0) {
        close(server_fd_);
    }
}

void Server::run(int port) {
    server_fd_ = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd_ < 0) {
        throw std::runtime_error("创建socket失败");
    }

    int opt = 1;
    setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);

    if (bind(server_fd_, (struct sockaddr*)&address, sizeof(address)) < 0) {
        close(server_fd_);
        throw std::runtime_error("绑定端口失败");
    }

    if (listen(server_fd_, 10) < 0) {
        close(server_fd_);
        throw std::runtime_error("监听端口失败");
    }

    std::cout << "服务器运行在端口 " << port << std::endl;
    std::cout << "访问 http://localhost:" << port << std::endl;

    while (running) {
        struct sockaddr_in client_addr;
        socklen_t client_len = sizeof(client_addr);
        int client_fd = accept(server_fd_, (struct sockaddr*)&client_addr, &client_len);
        if (client_fd < 0) {
            if (errno == EINTR) { // 被信号中断
                continue;
            }
            std::cerr << "接受连接失败: " << strerror(errno) << std::endl;
            continue;
        }

        // 为每个客户端创建新线程
        std::thread client_thread(handleClient, client_fd, this);
        client_thread.detach();
    }

    std::cout << "服务器停止运行" << std::endl;
    close(server_fd_);
}
